<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://lib.baomitu.com/vue/2.7.7/vue.js"></script>
    <script src="https://lib.baomitu.com/axios/latest/axios.js"></script>
  </head>

  <body>
    <div id="app">
      <div>
        <input v-model="username" />
        <input v-model="password" />
      </div>
      <div>
        <button @click="login">登录</button>
        <button @click="logout">登出</button>
        <button @click="getUser">获取普通用户数据</button>
      </div>
    </div>
    <script>
      axios.defaults.baseURL = "http://localhost:3000";
      axios.interceptors.request.use((config) => {
        const token = localStorage.getItem("token");
        if (token) {
          // 如果 token 存在，在每个 HTTP header 都加上 token
          // Bearer 是 JWT 的认证头部信息
          config.headers.common["Authorization"] = `Bearer ${token}`;
        }
        return config;
      });
      const app = new Vue({
        el: "#app",
        data: {
          username: "王五",
          password: 123,
        },
        methods: {
          async login() {
            console.log("login");
            const res = await axios.post("/api/login", {
              username: this.username,
              password: this.password,
              type: "common",
            });
            console.log(res);
            //将token设置到localStorage中
            localStorage.setItem("token", res.data.token);
          },
          async logout() {
            localStorage.removeItem("token");
          },
          async getUser() {
            try {
              var res = await axios.get("/api/user?type=common");
              console.log(res);
            } catch (err) {
              console.log(err);
            }
          },
        },
      });
    </script>
  </body>
</html>
